package at.fhv.dcs.aw.j2me.gps.gpsReader;

import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

/* gpsReq.java
 * 
 * Alfred Olschnoegger
 * 19.05.2008
 */

/**
 * TODO description
 * 
 * @date 19.05.2008
 * @author Alfred Olschnoegger
 */

public class gpsReader extends Thread implements LocationListener {

	private static final int s_Timeout = 60;
	private static final int s_MaxAge = 4;

	private float m_Altitude = 0;
	private double m_Latitude = 0;
	private double m_Longitude = 0;

	private boolean m_Available = false;

	private gpsReader_Observer m_Observer;

	gpsReader(gpsReader_Observer observer) {
		m_Observer = observer;
	}

	public void run() {
		initGPS();
	}

	private void initGPS() {
		// setting up the criterias
		Criteria crit1 = new Criteria();
		crit1.setHorizontalAccuracy(500); // 5m
		//crit1.setVerticalAccuracy(1); // 5m
		//crit1.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
		//crit1.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
		//crit1.setCostAllowed(false);
		//crit1.setSpeedAndCourseRequired(true);
		//crit1.setAltitudeRequired(true);
		//crit1.setAddressInfoRequired(true);
		LocationProvider provider = null;

		while (provider == null) {
			try {
				provider = LocationProvider.getInstance(crit1);
				if (provider != null) {
					provider.setLocationListener(this,-1, s_Timeout, s_MaxAge);
					m_Available = true;
					
					
				}
				
			} catch (LocationException le) {
				m_Available = false;
			}
			m_Observer.updateState();
			m_Observer.updateLocation();

			try {
				sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//provider.notify();
		}
	}

	public float getAltitude() {
		return m_Altitude;
	}

	public double getLatitude() {
		return m_Latitude;
	}

	public double getLongitude() {
		return m_Longitude;
	}

	public void locationUpdated(LocationProvider provider, final Location location) {
		QualifiedCoordinates coord = location.getQualifiedCoordinates();
		m_Latitude = coord.getLatitude();
		m_Longitude = coord.getLongitude();
		m_Altitude = coord.getAltitude();
		
		m_Observer.updateLocation();
	}

	public void providerStateChanged(LocationProvider provider, final int newState) {

		if (newState == LocationProvider.AVAILABLE) {
			m_Available = true;
		} else {
			m_Available = false;
		}
		m_Observer.updateState();
		m_Observer.updateLocation();
	}

	public boolean isAvailable() {
		return m_Available;
	}
}

// end of gpsReq.java
